var $ResultSeed;
var Players;
var Winers;
var audio_Running,
audio_GetOne;
var tagList ="" ;
var numList ="" ;
var buttonurl;
var hasnd;
var cj_per = []; 
var resizePart = window.WBActivity.resize = function() {};
var start = window.WBActivity.start = function() {
    window.WBActivity.hideLoading();
    $(".usercount-label").html("加载数据中...");
    $(".control").hide();
	cj_ready();
	progressLuckBar();
    $(".Panel.Top").css({
        top: 0
    });
    $(".Panel.Bottom").css({
        bottom: 0
    });
    $(".Panel.Lottery").css({
        display: "block",
        opacity: 1
    });
	
    $ResultSeed = $(".lottery-right .result-line");
    $(".control.button-run").on("click", 
    function() {
        start_lottory()
    });
    $(".control.button-stop").on("click", 
    function() {
        stop_lottory()
    });
   
};
var getUser = function(id,f) {
	for(var i = 0;i < id.length; i++) {
		$(".lottery-right").scrollTop(0);
	    var b = $(".lottery-right").scroll(0).children(".result-line").length - 1;
	    var a = $ResultSeed.clone();
		a.addClass('had_luck_user');
	    a.find(".result-num").html((b + 1));
	    a.prependTo(".lottery-right").slideDown();
	    var e = a.offset();
	    var c = $(".lottery-run .user:eq(" + i +")");
	    var d = c.clone().appendTo("body").css({
	        position: "absolute",
	        top: c.offset().top,
	        left: c.offset().left,
	        width: c.width(),
	        height: c.height()
	    }).animate({
	        width: 60,
	        height: 60,
	        top: e.top + 5,
	        left: e.left + 50
	    },
	    500, 
	    function() {
	        var g = d.css("background-image");
	        d.appendTo(a).removeAttr("style").css({
	            "background-image": g
	        });
			a.find("i").attr('onclick','delLuckUser('+id[i]+');');
	        if ($.isFunction(f)) {
	            f.call(this)
	        }
	    })
	}
};
var progressLuckBar = function(){
   $.ajax({
		url:PATH_ACTIVITY + Path_url('lottory_taglist'),
		data:{rid: scene_id},
    	type:"post",
		dataType:'json',
    	success:function(d){
    		if(d.result == 0 && d.data.length > 0){
	    		$.each(d.data,function(i,val){
	    			$("#tagid").append('<option value='+val.id+'>'+val.tag_name+'</option>');
	    		})
    		}
			var user = cj_per.length;
			$(".usercount-label").html(user + "人");
			$(".control.button-run").fadeIn();
    	}
    });
}
var cj_ready = function () {	
   cj_per = [];
   $.ajax({
		url:PATH_ACTIVITY + Path_url('lottory_user'),
    	data:{rid: scene_id},
    	type:"post",
		dataType:'json', 
		async:false,
    	success:function(json){
			if(json.ret==0 && json.data.length>0){
				cj_per = json.data;
				console.log(cj_per.length);
			}
    	}
    });
}
function getCurrentInfo(){
	cj_ready();
	var option = $("#tagid option:selected").val();
	if(option>-1){
	var luckid = $("#luckid").val();
	$.ajax({
		url:LUCKCONTENT,
    	data:{"luckid":luckid,"luckTag.id":option},
    	type:"post",
		async:true,
		dataType:'json',  
    	success:function(data){
			var signNum = cj_per.length;
		    var joinNum = signNum;
		  
		    $("#luckname").val(data.map.luck_name);
		    $("#tagNum").val(data.map.tagNum);
			joinNum = parseInt(signNum)-parseInt(data.map.num==undefined?0:data.map.num);
			$("#may_num").html(joinNum>0?joinNum:0);
    	}
    });
	getLuckUser(luckid,option);
  }
}
function tip(msg,autoClose){
	var div = $("#poptip");
	var content =$("#poptip_content");
	if(div.length<=0){
		div = $("<div id='poptip'></div>").appendTo(document.body);
		content =$("<div id='poptip_content'>" + msg + "</div>").appendTo(document.body);
	}else{
		content.html(msg);
		content.show(); div.show();
	}
	if(autoClose) {
		setTimeout(function(){
			content.fadeOut(500);
			div.fadeOut(500);
		},1000);
	}
}
function tip_close(){
	$("#poptip").fadeOut(500);
	$("#poptip_content").fadeOut(500);
}

function changeLuck(obj){//改变奖项
	var option = obj;
	if(option==-1){
		 return;
	}
	$("#loading").show();
	$(".lottery-right .had_luck_user").remove();
	cj_ready();
	var user = cj_per.length;
	$(".usercount-label").html(user + "人");
	$(".control.button-run").fadeIn();
		$.ajax({
			url:PATH_ACTIVITY + Path_url('lottory_one_award'),
			data:{"rid":scene_id,"award_id":option},
			type:"post",
			async:true,
			dataType:'json',  
			success:function(d){
				/*$(".lottery-run .user").css({
					"background-image": "url(" + d.data.luck_img + ")"
				});
				$(".lottery-run .user .nick-name").html(d.data.luck_name);
				*/
				$("#tag_num").val(d.data.tag_num);
				getLuckUser(option);	
				$("#loading").hide();
			}
		});
}

var getLuckUser = function (option){
    $.ajax({
		url:PATH_ACTIVITY + Path_url('lottory_luck_user'),
    	data:{"rid":scene_id,"award_id":option},
    	type:"post",
    	dataType:'json',
    	success:function(d){
		    if(d.data.length>0){
				$.each(d.data,function(i,val){
					var list_num = i +1;
					var luck_user = '<div class="result-line had_luck_user" style="display: block;">';
						luck_user += '<div class="result-num">'+list_num+'</div>';
						luck_user += '<i class="delLottery" onclick="delLuckUser('+val.id+')"></i>';
							luck_user += '<div class="user" style="background-image: url('+val.avatar+');">';
							luck_user += '<span class="nick-name">'+val.nick_name+'</span></div></div>';
						$(".lottery-right").prepend(luck_user);
				})
					
		    }
    	}
    });
}

function showLayer(i){
	$("#layer"+i).fadeIn();
	$("body").append("<div class=\"layerBlank\"></div>");
};
function closeLayer(o){
	$(o).parents(".layerStyle").hide();
	$("div").remove(".layerBlank");
};

function confirmLayer(openid,luckid){
	$("#layer2").fadeIn();
	$("body").append("<div class=\"layerBlank\"></div>");
	$("#layer2 :button:eq(0)").off().on("click",function(){
		delLuckUser(openid,luckid);
    })
};

function delLuckUser(list_id){
	var option = $("#tagid option:selected").val();
    $.ajax({
		url:PATH_ACTIVITY + Path_url('lottory_remove_user'),
    	data:{"rid":scene_id,"award_id":option,"list_id":list_id},
    	type:"post",
    	async:true,
    	success:function(data){
    		var base = $(".usercount-label").html();
			base = base.replace("人","");
			var person_now = parseInt(base)+1>0?parseInt(base)+1:0;
			$(".usercount-label").html(person_now+"人");
   			$(".lottery-right .had_luck_user").remove();
			cj_ready();
			getLuckUser(option);
    	}
    });
}
Array.prototype.indexOf = function(val) {            
	for (var i = 0; i < this.length; i++) {
		if (this[i] == val) return i;
	}
	return -1;
};
Array.prototype.remove = function(val) {
	var index = this.indexOf(val);
	if (index > -1) {
		this.splice(index, 1);
	}
};
function reset(){
	var option = $("#tagid option:selected").val();
	if($(".lottery-right .had_luck_user").length==0){
		return;
	}
	if(option>-1){
		if(confirm("重新抽奖、数据将无法恢复，确定吗？")){
			$.ajax({
				url:PATH_ACTIVITY + Path_url('lottory_reset_user'),
				data:{"rid":scene_id,"lottory_id":option},
				type:"post",
				async:true,
				success:function(data){
					$(".lottery-right .had_luck_user").remove();
					cj_ready();
					$(".usercount-label").html(cj_per.length+"人");
				}
			});
	    }
   }
}
function changeClick(){
	$(".control.button-run").attr('onclick','');  
	$(".control.button-run").unbind('click');
	$(".control.button-run").click(function(){  
	   alert("正在进行，不能点击");
	});  
		
	$(".control.button-stop").attr('onclick',''); 
	$(".control.button-stop").unbind('click');
	$(".control.button-stop").click(function(){  
	  alert("正在进行，不能点击");
	});  
	
	$("#newLuckButton").attr('onclick','');    
	$("#newLuckButton").unbind('click');
	$("#newLuckButton").click(function(){  
	  alert("正在进行，不能点击");
	});  
	$(".button-reload").attr('onclick','');    
	$(".button-reload").unbind('click');
	$(".button-reload").click(function(){  
	  alert("正在进行，不能点击");
	});  
}

function recoverClick(){
	$(".control.button-run").attr('onclick',''); 
	$(".control.button-stop").attr('onclick',''); 
	$("#newLuckButton").attr('onclick','');

	$(".control.button-run").unbind('click');
	$(".control.button-stop").unbind('click');
	$("#newLuckButton").unbind('click','');
	$(".button-reload").unbind('click');
	
	$(".control.button-run").attr('onclick','start_lottory()');  //此方法如不起作用，可使用“ $(this).unbind('click');”  代替  
	$(".control.button-stop").attr('onclick','stop_lottory()');  //此方法如不起作用，可使用“ $(this).unbind('click');”  代替  
	$("#newLuckButton").attr('onclick','javascript:reset();');  //此方法如不起作用，可使用“ $(this).unbind('click');”  代替 
	$(".button-reload").attr('onclick','javascript:window.location.reload();');
}

var isChange=true;
var num;
var timer;
var numPrizeName;
var numPrizeArray;
var luck_num;
function start_lottory(i){
	var option = $("#tagid option:selected").val();
	if(option==-1){
		alert('请选择奖项');
		return false; 
	}
	//已经中奖的人数
	var alreadyNum = $(".result-line").length - 1;
	//奖品数量
	var tagNum = $("#tag_num").val() == "" ? 0 : $("#tag_num").val();
	if(alreadyNum !=0 && alreadyNum == parseInt(tagNum)){
		$("#tagid").removeAttr("disabled");
	    $(".control.button-run").html("开始抽奖");
		clearInterval(timer);
		num = 0;
		isChange = true;
	    recoverClick();
		//alert('亲，当前奖项已经抽满人数，不能再进行抽奖！');
		return false;
	}   
	if(cj_per.length == 0){
		$("#tagid").removeAttr("disabled");
	   $(".control.button-run").html("开始抽奖");
		clearInterval(timer);
		num = 0;
		isChange = true;
	    recoverClick();
		//alert('参与抽奖人数太少没法抽了！！');
		return false;
	}   
		  
	if(i!=2){
		num=parseInt($("#num option:selected").val());
		var base = $(".usercount-label").html();
		base = base.replace("人",""); 
		if(parseInt(base)==0){
			//alert('可抽奖人数为0！不能再进行抽奖');
			return false;
		}
		$("#tagid").attr("disabled","disabled");
	}
	timer=setInterval(function(){
		changeNum();
	},120)
	$(".control.button-run").fadeOut();
	$(".control.button-stop").fadeIn();

	return true;
}

function stop_lottory(){
	var option = $("#tagid option:selected").val();
	var count = 0;
	if(!numPrizeArray || numPrizeArray.length == 0) return;
	for(var i=0;i<cj_per.length;i++){
	    if(cj_per[i].nd_id == option){
			numPrizeArray[count] = cj_per[i];
			if(!numPrizeArray[count]) break;
			//luck_num = i;
			$(".lottery-run .user:eq(" + count + ")").css({
				"background-image": "url(" + numPrizeArray[count].avatar + ")"
			});
			$(".lottery-run .user .nick-name:eq(" + count + ")").html(numPrizeArray[count].nick_name);
			count++;
			if(count >= 9) break;
		}
	}
	for(var i = count; i < 10; i++) {
		if(numPrizeArray[count].nd_id != option && numPrizeArray[count].nd_id > 0) {
			var randomVal = Math.round(Math.random() * p_num);
			$(".lottery-run .user:eq(" + i + ")").css({
				"background-image": "url(" + numPrizeArray[i].avatar + ")"
			});
			$(".lottery-run .user .nick-name:eq(" + i + ")").html(numPrizeArray[i].nick_name);
		}
	}
	$(".control.button-run").fadeIn()
	$(".control.button-stop").fadeOut()
	clearInterval(timer);//清除定时器 不在滚动
	var base = $(".usercount-label").html();
	base = base.replace("人",""); 
	checked();
	$("#tagid").removeAttr("disabled");
	$(".control.button-run").html("开始抽奖");
	isChange = true;
	recoverClick();
}


function checked(){
	    var comment = "幸运奖";
        //console.log(numPrizeArray);
	    for(i = 0;i < numPrizeArray.length;i++) {
			var list_num = $(".result-line").length
			var luck_user = '<div class="result-line had_luck_user" style="display: block;">';
			luck_user += '<div class="result-num">'+list_num+'</div>';
			luck_user += '<div class="user" style="background-image: url('+numPrizeArray[i].avatar+');">';
			luck_user += '<span class="nick-name">'+numPrizeArray[i].nick_name+'</span></div></div>';
			$(".lottery-right").prepend(luck_user);
		}
	    for(var i = 0 ;i < numPrizeArray.length; i++) {
	    	cj_per.remove(numPrizeArray[i]);
	    	$(".usercount-label").html(cj_per.length+"人");
	    }
	    //console.log(numPrizeArray);
		$.ajax({
			url:PATH_ACTIVITY + Path_url('lottory_save_user'),
			data:{"rid":scene_id,users : numPrizeArray,"award_id":$("#tagid option:selected").val(),"award_name":comment},
			type:"post",
			dataType:'json',
			async:true,
			timeout:0,//永不超时
			success:function(d){
				/*getUser(d.data,function(){
					numPrizeArray = [];
				});*/
				//getLuckUser(13);
			}
		});

		//cj_per.splice(luck_num,1);
	   
}

function changeNum(){
	var p_num = cj_per.length - 1;
	var randomVal = Math.round(Math.random() * p_num);
	//每次抽出10位幸运用户
	numPrizeArray = getArrayItems(cj_per,10);
    //numPrizeName = cj_per[randomVal];
	//luck_num = randomVal;
	for(var i = 0; i < 10 && i < numPrizeArray.length; i++) {
		$(".lottery-run .user:eq("+i+")").css({
	        "background-image": "url(" + numPrizeArray[i].avatar + ")"
	    });
	    $(".lottery-run .user .nick-name:eq("+i+")").html(numPrizeArray[i].nick_name);
	}
}
//从一个给定的数组arr中,随机返回num个不重复项
function getArrayItems(arr, num) {
    //新建一个数组,将传入的数组复制过来,用于运算,而不要直接操作传入的数组;
    var temp_array = new Array();
    /*for (var index in arr) {
        temp_array.push(arr[index]);
    }*/
    for(var i = 0;i< arr.length;i++) {
        temp_array.push(arr[i]);
	}
   //console.log(temp_array);
    //取出的数值项,保存在此数组
    var return_array = new Array();
    for (var i = 0; i<num; i++) {
        //判断如果数组还有可以取出的元素,以防下标越界
        if (temp_array.length>0) {
            //在数组中产生一个随机索引
            var arrIndex = Math.floor(Math.random() * temp_array.length);
            //console.log('随机数：'+ arrIndex);
            //console.log('总长度：'+ temp_array.length);
            //将此随机索引的对应的数组元素值复制出来
            return_array[i] = temp_array[arrIndex];
            //console.log(temp_array);
            //然后删掉此索引的数组元素,这时候temp_array变为新的数组
            temp_array.splice(arrIndex, 1);
        } else {
            //数组中数据项取完后,退出循环,比如数组本来只有10项,但要求取出20项.
            break;
        }
    }
    return return_array;
}
$(function(){
	getLuckUser(13);
	window.running = false;
	$(document).keyup(function (e) {
		if(!window.running) {
			if (e.keyCode == 32){
				if(start_lottory()){
					window.running = true;
					setTimeout(function(){
						stop_lottory();
						window.running = false;
					},2000);
				}
			}
			
		} 
		
	});
});
